const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const rect = canvas.getBoundingClientRect()

canvas.width = 500;
canvas.height = 700;

const explusions = [];

class Explusion {
    constructor(x, y) {
        this.spriteWidth = 200;
        this.spriteHeight = 179;
        this.width = this.spriteWidth / 2;
        this.height = this.spriteHeight / 2;
        this.x = x;
        this.y = y;
        this.image = new Image();
        this.image.src = "./explusion.png";
        this.frame = 0;
        this.timer = 0;
        this.angle = Math.random() * 6.2;
        this.sound = new Audio();
        this.sound.src = "boom.wav";
    }
    update() {
        if(this.frame===0)this.sound.play();
        this.timer++;
        if (this.timer % 10 === 0) {
            this.frame++;
        }

    }
    draw() {
        ctx.save();
        ctx.translate(this.x, this.y);
        ctx.rotate(this.angle);
        ctx.drawImage(this.image, this.frame * this.spriteWidth, 0, this.spriteWidth, this.spriteHeight, 0 - this.width / 2, 0 - this.height / 2, this.width, this.height);
        ctx.restore();
    }
}


canvas.addEventListener('click', (e) => {
    createAnimation(e)
});

// canvas.addEventListener('mousemove',(e)=>{
//     createAnimation(e);
// })

function createAnimation(e) {
    const positionX = e.x - rect.left;
    const positionY = e.y - rect.top;
    explusions.push(new Explusion(positionX, positionY));
}


function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (let i = 0; i < explusions.length; i++) {
        const explusionObj = explusions[i];
        explusionObj.update();
        explusionObj.draw();

        if (explusionObj.frame > 5) {
            explusions.splice(i, 1);
            i--;
        }
    }
    requestAnimationFrame(animate)
}
animate()